package com.woniu.commons.util;


import cn.hutool.json.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.io.*;
import java.net.*;
import java.security.Key;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class JwtUtil {
    //自定义秘钥
    static String secretKey = "ksaasfdasdfadsfwfrasdfsadffcasijfasadfasfdlkfjlasjflksajfd";
    
    /**
     * 生成JWT Token
     *
     * @param body             要包含在Token中的用户信息
     * @param expiresInMinutes Token的有效时长（分钟）
     * @return 生成的Token字符串
     */
    public static String createToken(Map<String, Object> body, Integer expiresInMinutes) {
        Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
        Date expirationDate = new Date(System.currentTimeMillis() + expiresInMinutes * 60 * 1000);
        return Jwts.builder().setClaims(body).setExpiration(expirationDate).signWith(key).compact();
    }
    
    /**
     * 解析JWT Token
     *
     * @param token 要解析的Token字符串
     * @return 解析出的Token的Claims对象，包含了用户信息等内容
     */
    public static Claims parseToken(String token) {
        Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }
    
    /**
     * 获取用户的ID
     *
     * @param token 要解析的Token字符串
     * @return 解析出用户的ID
     */
    public static Object getSubject(String token) throws Exception {
        return parseToken(token).get("subject");
    }
    public static Object getData(String token,String key){
        Claims claims = parseToken(token);
        return claims.get(key);
    }


//    /**
//     * 实名认证
//     * @param cardId
//     * @param realName
//     * @return
//     */
//    public static String realNameAuthentication(String cardId,String realName){
//        String host = "https://idenauthen.market.alicloudapi.com"; // 【1】请求地址 支持http 和 https 及 WEBSOCKET
//        String path = "/idenAuthentication";// 【2】后缀
//        String appcode = "cf7c4f7956d64da6ace6be2989800edc"; // 【3】开通服务后 买家中心-查看AppCode
//        String idCard = cardId;// 【4】请求参数，详见文档描述
//        String name = realName;// 【4】请求参数，详见文档描述
//        try {
//            String urlSend = host + path + "?idCard=" + idCard + "&name="+ URLEncoder.encode(name, "UTF-8");// 【5】拼接请求链接
//            URL url = new URL(urlSend);
//            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
//            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);//格式Authorization:APPCODE (中间是英文空格)
//            int httpCode = httpURLCon.getResponseCode();
//            if (httpCode == 200) {
//                String json = read(httpURLCon.getInputStream());
//                System.out.println("正常请求计费(其他均不计费)");
//                System.out.println("获取返回的json：");
//                System.out.print(json);
//                int index = json.lastIndexOf("status");
//                String str = json.substring(index + 9, index + 11);
//                if (!str.equals("01")) return "实名认证失败，请重试";
//            } else {
//                Map<String, List<String>> map = httpURLCon.getHeaderFields();
//                String error = map.get("X-Ca-Error-Message").get(0);
//                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
//                    System.out.println("AppCode错误");
//                    return "AppCode错误 ";
//                } else if (httpCode == 400 && error.equals("Invalid Url")) {
//                    System.out.println("请求的 Method、Path 或者环境错误");
//                    return "请求的 Method、Path 或者环境错误 ";
//                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
//                    System.out.println("参数错误");
//                    return "参数错误 ";
//                } else if (httpCode == 403 && error.equals("Unauthorized")) {
//                    System.out.println("服务未被授权（或URL和Path不正确）");
//                    return "服务未被授权（或URL和Path不正确）";
//                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
//                    System.out.println("套餐包次数用完 ");
//                    return "套餐包次数用完 ";
//                } else if (httpCode == 403 && error.equals("Api Market Subscription quota exhausted")) {
//                    System.out.println("套餐包次数用完，请续购套餐");
//                    return "套餐包次数用完，请续购套餐 ";
//                } else {
//                    System.out.println("参数名错误 或 其他错误");
//                    System.out.println(error);
//                    return "参数名错误 或 其他错误 ";
//                }
//            }
//        } catch (MalformedURLException e) {
//            System.out.println("URL格式错误");
//            return "URL格式错误";
//        } catch (UnknownHostException e) {
//            System.out.println("URL地址错误");
//            return "URL地址错误";
//        } catch (Exception e) {
//            // 打开注释查看详细报错异常信息
//            e.printStackTrace();
//            return "实名认证失败";
//        }
//        return "true";
//    }
//
//    private static String read(InputStream is) throws IOException {
//        StringBuffer sb = new StringBuffer();
//        BufferedReader br = new BufferedReader(new InputStreamReader(is));
//        String line = null;
//        while ((line = br.readLine()) != null) {
//            line = new String(line.getBytes(), "utf-8");
//            sb.append(line);
//        }
//        br.close();
//        return sb.toString();
//    }
private static final String HOST = "https://idenauthen.market.alicloudapi.com";
    private static final String PATH = "/idenAuthentication";
    private static final String APPCODE = "cf7c4f7956d64da6ace6be2989800edc";

    public static String realNameAuthentication(String idNo, String realName) {
        try {
            URL url = new URL(HOST + PATH);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestMethod("POST");
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + APPCODE);
            httpURLCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 构建请求参数
            String data = "idNo=" + URLEncoder.encode(idNo, "UTF-8") + "&name=" + URLEncoder.encode(realName, "UTF-8");

            // 发送请求参数
            httpURLCon.setDoOutput(true);
            try (OutputStream os = httpURLCon.getOutputStream()) {
                os.write(data.getBytes("UTF-8"));
            }

            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("获取返回的json：" + json);
                if (json.contains("\"respCode\":\"0000\"")) {
                    return "实名认证通过"+json;
                } else {
                    return "实名认证失败，请重试";
                }
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                return handleHttpError(httpCode, error);
            }
        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
            return "URL格式错误";
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
            return "URL地址错误";
        } catch (Exception e) {
            e.printStackTrace();
            return "实名认证失败";
        }
    }

    private static String read(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }

    private static String handleHttpError(int httpCode, String error) {
        switch (httpCode) {
            case 400:
                if (error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误");
                    return "AppCode错误";
                } else if (error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                    return "请求的 Method、Path 或者环境错误";
                } else if (error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                    return "参数错误";
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                    return "参数名错误 或 其他错误";
                }
            case 403:
                if (error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                    return "服务未被授权（或URL和Path不正确）";
                } else if (error.equals("Quota Exhausted") || error.equals("Api Market Subscription quota exhausted")) {
                    System.out.println("套餐包次数用完，请续购套餐");
                    return "套餐包次数用完，请续购套餐";
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                    return "参数名错误 或 其他错误";
                }
            default:
                System.out.println("参数名错误 或 其他错误");
                System.out.println(error);
                return "参数名错误 或 其他错误";
        }
    }

    
}
